﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Enterprise.Management.Data;
using System.Data.Linq.SqlClient;
using Enterprise.Management.Common;
using Enterprise.Management.ViewModels;

namespace Enterprise.Management.Business
{
    public class ManagementBLL : BaseBLL
    {
        public const string DEFAULT_USER_PASSWORD = "123123";

        #region DP_Role
        public List<DP_Role> GetRolesWithoutOwner(RoleType role)
        {
            return DataContext.DP_Role.Where(m => m.Role_ID != (int)role).ToList();
        }
        #endregion

        #region DP_User
        public DP_User GetUser(string email)
        {
            return DataContext.DP_User.FirstOrDefault(m => m.User_Email == email && m.User_Status == (int)StatusType.Valid);
        }

        public DP_User GetUser(int userID)
        {
            return DataContext.DP_User.First(m => m.User_ID == userID);
        }

        public List<DP_User> GetUsers()
        {

            return DataContext.DP_User.ToList();
        }

        public void AddUser(DP_User user)
        {
            user.User_Status = (int)StatusType.Valid;
            user.User_Pwd = Security.MD5(DEFAULT_USER_PASSWORD);
            DataContext.DP_User.InsertOnSubmit(user);
            DataContext.SubmitChanges();
        }

        public void UpdateUser(UpdateUserViewModel user)
        {
            DP_User dp_user = DataContext.DP_User.First(m => m.User_ID == user.User_ID);

            if (dp_user.User_Name != user.User_Name)
            {
                dp_user.User_Name = user.User_Name;
            }

            if (dp_user.User_Email != user.User_Email)
            {
                dp_user.User_Email = user.User_Email;
            }

            if (user.IsResetPwd)
            {
                dp_user.User_Pwd = Security.MD5(DEFAULT_USER_PASSWORD);
            }

            DataContext.SubmitChanges();
        }
        #endregion

        #region DP_Category
        public DP_Category GetCategory(string name)
        {
            return DataContext.DP_Category.FirstOrDefault(m => m.Category_Name == name && m.Category_Status == (int)StatusType.Valid);
        }

        public List<DP_Category> GetCategories(DeptCategoryLevelType level)
        {
            return DataContext.DP_Category.Where(m => m.Category_Level == (int)level).ToList();
        }

        public int AddCategory(DP_Category category)
        {
            category.Category_Status = (int)StatusType.Valid;
            DataContext.DP_Category.InsertOnSubmit(category);
            DataContext.SubmitChanges();
            return category.Category_ID;
        }
        #endregion
    }
}